

import React, { Component } from 'react'

export default class index extends Component {

  constructor(){
    super();
    this.state = {
      username:"范旭康",
      sex:"male",
      books:["vue"]
    }
  }

  changeUsername=(e)=>{
    this.setState({
      ...this.state,
      username:e.target.value
    })
  }

  changeSex=(e)=>{
    this.setState({
      ...this.state,
      sex:e.target.value
    })
  }

  changeBooks=(e)=>{
    console.log("changeBooks");
    let idx = this.state.books.indexOf(e.target.id);
    
    idx>-1?this.state.books.splice(idx,1):this.state.books.push(e.target.id);
    
     this.setState({
      ...this.state,
      books:[...this.state.books]
    },()=>{
      console.log("this.state.books",this.state.books);
    })
  }

  render() {
    console.log("render");
    return (
      <div>
        <h1>双向绑定</h1>
        <p>文本框双向绑定：</p>
        <input type="text" value={this.state.username} onChange={this.changeUsername} />
        <p>this.state.username：{this.state.username}</p>
        <p>单选按钮</p>
        <input type="radio" id="male" name='sex' checked={this.state.sex==='male'} onChange={this.changeSex} value="male" /><label htmlFor='male'>男</label>
        <input type="radio" id="female" name='sex' checked={this.state.sex==='female'}  onChange={this.changeSex} value="female" /><label htmlFor='female'>女</label>
        <p>当前选择的性别是：{this.state.sex} </p>
        <p>复选：</p>
        技术书籍：
        <p>
        <input type="checkbox" id='js'  name="books" checked={this.state.books.includes("js")} onChange={this.changeBooks} /><label htmlFor='js'>JavaScript红宝书</label>
        </p>
        <p>
        <input type="checkbox" id='vue'      name="books" checked={this.state.books.includes("vue")}  onChange={this.changeBooks}/><label htmlFor='vue'>Vue入门到精通</label>
        </p>
        <p>
        <input type="checkbox" id='computer' name="books" checked={this.state.books.includes("computer")} onChange={this.changeBooks}/><label htmlFor='computer'>深入理解计算机原理</label>
        </p>
        <p>
        <input type="checkbox" id='react'    name="books" checked={this.state.books.includes("react")} onChange={this.changeBooks}/><label htmlFor='react'>三天学会react</label>
        </p>
        <p>选择的书籍：{this.state.books}</p>

      </div>
    )
  }
}
